package com.hdmp.mybatis.aspect;

import com.hdmp.mybatis.aspect.annotation.HdDataSource;
import com.hdmp.mybatis.constant.DataSourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author BigFan
 * @create 2018/11/20 12:59 PM
 */
@Aspect
@Slf4j
@Component
@Order(-1)
public class DataSourceAspect {

    @Pointcut("@annotation(com.hdmp.mybatis.aspect.annotation.HdDataSource)")
    public void dataSourcePointCut(){

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        HdDataSource myDataSource = method.getAnnotation(HdDataSource.class);
        String sourceName;
        if (myDataSource == null) {
            log.error("无注解，读取默认的DataSource" + DataSourceEnum.MASTER.getValue());
            DataSourceContextHolder.setDataSource(DataSourceEnum.MASTER.getValue());
            sourceName = DataSourceEnum.MASTER.getValue();

        } else {
            log.error("设置有注解，读取声明的DataSource" + myDataSource.value().getValue());
            DataSourceContextHolder.setDataSource(myDataSource.value().getValue());
            sourceName = myDataSource.value().getValue();
        }

        try {
            return point.proceed();
        } finally {
            log.error("清楚数据源成功....." + sourceName);
            DataSourceContextHolder.clear();

        }
    }



}
